<template>
    <div class="bom-management">
      <!-- 基础信息 -->
      <div class="base-info">
        <h4 class="section-title">基础信息</h4>
        <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <div class="form-row">
          <el-form-item label="BOM编号:" :label-width="Eject.formLabelWidth">
            <el-input
              v-model="ruleForm.itemNumber"
              autocomplete="off"
              style="width: 180px; height: 30px"
              :readonly="ruleForm.autoGenerate"
              clearable
              @click.native="handleCodeClick"
            />
            <template #prepend>MO</template>
            <el-switch
              width="40"
              v-model="ruleForm.autoGenerate"
              active-text="自动生成"
              active-color="#67C23A"
              @change="handleSwitchChange"
            />
          </el-form-item>
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
           
            
          <el-form-item label="BOM主题" prop="bomTheme" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForm.bomTheme" />
          </el-form-item>
          <el-form-item label="默认BOM" prop="resource">
    <el-radio-group v-model="ruleForm.bomDefault">
      <el-radio label="是"></el-radio>
      <el-radio label="否"></el-radio>
    </el-radio-group>
  </el-form-item>
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
            <el-form-item label="版本" prop="bomVersion" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForm.bomVersion" />
          </el-form-item>
          <el-form-item label="成品类型" prop="bomType" style="flex: 1;">
            <el-select v-model="ruleForm.bomType" placeholder="请选择">
              <el-option label="超能胶水" value="超能胶水" />
              <el-option label="万能胶水" value="万能胶水" />
            </el-select>
          </el-form-item>
          <el-form-item label="成品名称" prop="bomName" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForm.bomName" />
          </el-form-item>

        </div>
     
        <div class="form-row" style="display: flex; justify-content: space-between;">
         
          <el-form-item label="日产量" prop="dayNum" style="flex: 1;">
            <el-input v-model="ruleForm.dayNum" />
          </el-form-item>
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
          <el-form-item label="备注" prop="bomNote" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForm.bomNote" />
          </el-form-item>
          <el-form-item label="BOM配件" prop="wIds" style="flex: 1;">
            <el-input v-model="ruleForm.wIds" />
          </el-form-item>
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
          <el-form-item label="工艺流程" prop="processFlowCode" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForm.processFlowCode" />
          </el-form-item>
          <el-form-item label="附件" prop="attachment" style="flex: 1;">
            <el-input v-model="ruleForm.attachment" />
          </el-form-item>
        </div>
       
        <el-form-item>
          <el-button type="primary" @click="submitForm()">
            添加
          </el-button>
          <el-button @click="handleClose()">关闭</el-button>
        </el-form-item>

      </el-form>
      </div>
  
      <!-- BOM配件 -->
      <div class="bom-components">
        <h4 class="section-title">BOM配件</h4>
        <div class="action-btns">
          <el-button type="primary" @click="dialogTableVisible = true" class="action-btn">添加</el-button>
        </div>
        <el-table :data="multion" border style="width: 100%; margin-top: 10px" class="custom-table">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" width="80">
            <template #default="{ row, $index }">{{ $index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="itemNumber" label="物品编号"></el-table-column>
          <el-table-column prop="itemName" label="物品名称"></el-table-column>
          <el-table-column prop="specificationModel" label="规格型号"></el-table-column>
          <el-table-column prop="unit" label="单位"></el-table-column>
          <el-table-column prop="brand" label="品牌"></el-table-column>
        </el-table>   
        <!-- 物品对话框 -->
        <el-dialog v-model="dialogTableVisible" title="物品管理" width="800">
        <el-table :data="componentList" border style="width: 100%; margin-top: 10px" class="custom-table" @selection-change="handchange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" width="80">
            <template #default="{ row, $index }">{{ $index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="itemNumber" label="物品编号"></el-table-column>
          <el-table-column prop="itemName" label="物品名称"></el-table-column>
          <el-table-column prop="specificationModel" label="规格型号"></el-table-column>
          <el-table-column prop="unit" label="单位"></el-table-column>
          <el-table-column prop="brand" label="品牌"></el-table-column>
          <el-table-column prop="itemType" label="物品类别"></el-table-column>
          <el-table-column prop="itemAttribute" label="物品分类"></el-table-column>
          <el-table-column prop="currentStock" label="总库存"></el-table-column>
          <el-table-column prop="sellingPrice" label="销售单价"></el-table-column>
          <el-table-column prop="purchasePrice" label="采购单价"></el-table-column>
        </el-table>
        <div class="button-group">
          <el-button type="primary"  class="action-btn" @click="additem">确定</el-button>
          <el-button type="primary" @click="dialogTableVisible=false" class="action-btn">关闭</el-button>
        </div>
        </el-dialog>
      </div>
  
      <!-- 工艺流程 -->
      <div class="process-flow">
        <h4 class="section-title">工艺流程</h4>
        <div class="action-btns">
          <el-button type="primary" @click="dialogTableVisible1 = true" class="action-btn">添加</el-button>
        </div>
        <el-table :data="protion" border style="width: 100%; margin-top: 10px" class="custom-table">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" width="80">
            <template #default="{ row, $index }">{{ $index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="processFlowCode" label="工序编码"></el-table-column>
          <el-table-column prop="processFlowName" label="工序名称"></el-table-column>
          <el-table-column prop="processNum" label="工序数量"></el-table-column>
          <el-table-column prop="responName" label="负责人"></el-table-column>
          <el-table-column prop="department" label="部门"></el-table-column>
          <el-table-column prop="desc" label="备注"></el-table-column>
        </el-table>
        <!-- 工艺对话框 -->
        <el-dialog v-model="dialogTableVisible1" title="工艺管理" width="800">
          <el-table :data="processList" border style="width: 100%; margin-top: 10px" class="custom-table" @selection-change="handchange1">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" width="80">
              <template #default="{ row, $index }">{{ $index + 1 }}</template>
            </el-table-column>
            <el-table-column prop="processFlowCode" label="工序编码"></el-table-column>
            <el-table-column prop="processFlowName" label="工序名称"></el-table-column>
            <el-table-column prop="processNum" label="工序数量"></el-table-column>
          </el-table>
          <div class="button-group">
            <el-button type="primary"  class="action-btn" @click="addProcess">确定</el-button>
            <el-button type="primary" @click="dialogTableVisible1=false" class="action-btn">关闭</el-button>
          </div>
        </el-dialog>
      </div>
  
      <!-- 附件 -->
      <div class="attachments">
        <el-upload
          ref="upload"
          class="upload-demo"
          action="https://localhost:7209/api/Bom/File"
          :limit="1"
          :auto-upload="true"
          :on-success="handleUploadSuccess"
        >
          <template #trigger>
            <el-button type="primary">上传文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip text-red">
              限制 1 个文件，新文件将覆盖旧文件
            </div>
          </template>
        </el-upload>
      </div>
  
      <!--结尾按钮 -->
      <div class="button-group">
        <el-button type="primary" @click="addBom" class="action-btn">确定</el-button>
        <el-button type="primary" @click="jump" class="action-btn">关闭</el-button>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage, type TableInstance } from 'element-plus';
  import axios from 'axios';
  import { genFileId } from 'element-plus'
  import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
  import { useRouter } from 'vue-router';
  const router = useRouter();
  const generateCode = () => {
    const timestamp = Date.now(); // 获取精确到毫秒的时间戳
    ruleForm.itemNumber = `CS${timestamp}`;
};

const Eject = reactive({
    dialogFormVisible: false,
    formLabelWidth: "100px",
    title: "",
    Isture: true,
    dialogVisible: false,
    edialogFormVisible:false,
    gongdialogFormVisible:false,
});
const handleSwitchChange = (val: boolean) => {
    ruleForm.autoGenerate = val;
    if (val) {
        generateCode(); // 开启自动生成时立即生成
    } else {
        ruleForm.itemNumber = ""; // 关闭时清空编号
    }
};

const handleCodeClick = () => {
    if (ruleForm.autoGenerate) {
        generateCode(); // 点击输入框时重新生成
    }
};

const apiUrl = import.meta.env.VITE_APP_API_URL;
  // 基础信息表单
  const baseForm = ref({
    "bomNo": "",
    "bomtop": "",
    "bomdef": true,
    "bomver": "",
    "itemType": "",
    "itemNumber": "",//物品编号
    "processFlowCode": "",//工艺编号
    "itemName": "",
    "bomNum": 0,
    "bomInfo": "",
    "isDelete": false
  });
  
  //#region 物品管理
  
    // 物品列表数据
    const componentList = ref([
    {
        "itemId": 0,
        "itemNumber": "",
        "itemName": "",
        "specificationModel": "",
        "unit": "",
        "itemCategory": "",
        "itemAttribute": "",
        "itemType": "",
        "stockLimit": 0,
        "itemValidityPeriod": "",
        "alarmDays": 0,
        "sellingPrice": 0,
        "status": true,
        "currentStock": 0,
        "barcode": "",
        "brand": "",
        "manufacturerModel": "",
        "purchasePrice": 0,
        "remarks": "",
        "logicalDelete": false
    }
    ]);
    // 物品列表展示
    const itemList=()=>{
      axios.get(apiUrl+'/T5/BOMguan/GetItemManagement',{
        
      })
      .then(res=>{
        componentList.value=res.data.data
      })
    }
    const multion=ref([])
    //选中物品列表复选框
    const handchange=(val:any)=>{
      multion.value=val
    }
    const ids=reactive([])//获取选中的物品编号
    const dialogTableVisible = ref(false)//物品对话框
    //点击确定获取物品编号
    const additem=()=>{
      multion.value.forEach((x:any) => {
        ids.push(x.itemNumber)
      });
      dialogTableVisible.value=false
    }
  //#endregion
  
  //#region 工艺流程管理
  
  // 工艺流程对象
  const processList = ref([]);
  // 工艺列表展示
  const proList=()=>{
  axios.get(apiUrl+"/T5/BOMguan/GetProcessFlow",{
    
  })
  .then(res=>{
    processList.value=res.data.data
  })
  }
  const protion=ref([])
  //选中工艺列表复选框
  const handchange1=(val:any)=>{
    protion.value=val
    console.log("选中的工艺列表",val)
  }
  const proids=reactive([])//获取选中的工艺编号
  const dialogTableVisible1 = ref(false)//工艺对话框
  //点击确定获取工艺编号
  const addProcess = () => {
    protion.value.forEach((x:any) => {
      proids.push(x.processFlowCode)
    });
    dialogTableVisible1.value=false
  };
  //#endregion
  
  //#region 系统编号
    // 定义系统编号是否选中
    const isSystemNumber = ref(false);
    // 生成随机编号函数（字母+数字组合）
    const generateRandomNumber = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZqwertyuiopasdfghjklzxcvbnm0123456789';
    let result = '';
    for (let i = 0; i < 8; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
    };
  
    // 处理系统编号复选框变化
    const handleSystemNumberChange = () => {
    if (isSystemNumber.value) {
      baseForm.value.bomNo = generateRandomNumber();
    } else {
      baseForm.value.bomNo = '';
    }
    };
  //#endregion
  
  
  //#region 上传文件
  //文件对象
  const image = reactive({
  "fileName": "",
  "filePath": "",
  "bomId": "",
  })
  // 上传成功回调
  const handleUploadSuccess = (response: string, file: UploadRawFile) => {
    console.log('原始响应:', response);
  // 1. 保存文件信息到 reactive 对象
  image.fileName = file.name;
  image.filePath = response;
  // 2. 调用数据库接口保存文件信息
  Addimage();
  };
  
  //文件添加
  const Addimage=()=>{
  console.log("image",image)
  image.bomId = baseForm.value.bomNo
  axios.post('https://localhost:7209/api/File/AddFile',image)
  .then(res=>{
    if(res.data.code==100){
      ElMessage.success("上传成功")
    }
    else{
      ElMessage.error("上传失败")
    }
  })
  }
  
  //#endregion
  
  const ruleForm = reactive({
    bomId: 0,
    itemNumber: "",
    bomTheme: "",
    bomDefault: "",
    bomVersion: "",
    bomType: "",
    bomName: "",
    dayNum: "",
    bomNote: "",
    wIds: "",
    processFlowCode: "",
    attachment: "",
    isDeleted: false,
    autoGenerate: false, // 是否自动生成
});

  // 新增bom数据
  const addBom = () =>{
    baseForm.value.itemNumber=ids.join(',')
    baseForm.value.processFlowCode=proids.join(',')
    console.log("物品编号1",baseForm.value.itemNumber)
    axios.post(apiUrl+"/T6/BOMguan/AddBOMguans",baseForm.value)
    .then(res=>{
      if(res.data.code==100){
        ElMessage.success(res.data.msg)
        router.push('/GetBom');
      }
      else{
        ElMessage.error(res.data.msg)
      }
    })
    
  };
  
  // 关闭bom页面
  const jump = () => {
    router.push('/GetBom');
  };
  //钩子
  onMounted(()=>{
      itemList()//物品展示
      proList()//工艺展示
  })
  </script>
  
  <style scoped>
  .bom-management {
    max-width: 1200px;
    margin: 0 auto;
    padding: 30px 20px;
    background: #fff;
  }
  
  .section-title {
    color: #2c3e50;
    font-size: 18px;
    margin-bottom: 20px;
    padding-bottom: 8px;
    border-bottom: 2px solid #e0f2f1;
  }
  
  .form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 15px;
    align-items: center;
  }
  
  .disabled-input {
    background: #f8f9fa;
    cursor: not-allowed;
  }
  
  .rounded-input {
    border-radius: 6px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  }
  
  .select-style {
    width: 200px;
    border-radius: 6px;
  }
  
  .textarea-style {
    border-radius: 6px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  }
  
  .custom-table {
    --el-table-border-color: #e4e7ed;
    --el-table-header-background-color: #f5f7fa;
    border-radius: 6px;
    overflow: hidden;
  }
  
  .table-input {
    width: 80px;
    margin: 0 auto;
  }
  
  .action-btns {
    margin-bottom: 10px;
    display: flex;
    gap: 10px;
  }
  
  .action-btn {
    padding: 8px 16px;
    border-radius: 4px;
  }
  
  .upload-file {
    border: 1px solid #e4e7ed;
    padding: 10px;
    margin-top: 10px;
    border-radius: 4px;
    background: #fff;
  }
  
  .button-group {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 15px;
  }
  .base-info{
    background: #fff;
  }
  </style>